<template>
  <div class="comments-manage">
    <div class="page-header">
      <h1 class="page-title">评论管理</h1>
    </div>

    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="已隐藏" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column label="用户" >
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.userInfo?.avatar || '/logo.svg'" :size="32" />
              <span>{{ row.userInfo?.nickname || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容"  show-overflow-tooltip />
        <el-table-column prop="likeCount" label="点赞数"  />
        <el-table-column label="回复数" >
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewReplies(row)">
              {{ row.replyCount || 0 }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" >
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '已隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" >
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleToggleStatus(row)">
              {{ row.status === 1 ? '隐藏' : '显示' }}
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复列表对话框 -->
    <el-dialog v-model="repliesVisible" title="评论回复" width="800px">
      <el-table :data="repliesData" v-loading="repliesLoading">
        <el-table-column label="回复用户" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.user?.avatar || '/logo.svg'" :size="32" />
              <span>{{ row.user?.nickname || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="回复内容" min-width="300" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button link type="danger" size="small" @click="handleDeleteReply(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommentsList, deleteComment, updateCommentStatus, getCommentRepliesList, deleteCommentReply } from '@/api/admin'

const loading = ref(false)
const repliesLoading = ref(false)
const tableData = ref([])
const repliesData = ref([])
const repliesVisible = ref(false)
const currentCommentId = ref('')

const searchForm = reactive({
  contentId: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getCommentsList(params)
    console.log("评论数据",res)
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.contentId = ''
  searchForm.status = ''
  handleSearch()
}

const handleToggleStatus = (row: any) => {
  const newStatus = row.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '显示' : '隐藏'
  
  ElMessageBox.confirm(`确定${action}该评论吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateCommentStatus(row._id, newStatus)
      ElMessage.success(`${action}成功`)
      loadData()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  })
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除该评论吗？删除后将同时删除所有回复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteComment(row._id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleViewReplies = async (row: any) => {
  currentCommentId.value = row._id
  repliesVisible.value = true
  repliesLoading.value = true
  try {
    const res = await getCommentRepliesList(row._id, { page: 1, pageSize: 100 })
    repliesData.value = res.data || []
  } catch (error) {
    ElMessage.error('加载回复列表失败')
  } finally {
    repliesLoading.value = false
  }
}

const handleDeleteReply = (row: any) => {
  ElMessageBox.confirm('确定删除该回复吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCommentReply(row._id)
      ElMessage.success('删除成功')
      handleViewReplies({ _id: currentCommentId.value })
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

const formatTime = (timestamp: any) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.comments-manage {
  width: 100%;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      font-size: 14px;
      color: #333;
    }
  }
}
</style>

